<!--
 * @Description: Stay hungry，Stay foolish
 * @Author: ''
 * @Date: 2023-09-18 18:03:31
 * @LastEditTime: 2023-09-19 13:47:20
 * @LastEditors: ''
-->
<template>
  <div
    ref="reference"
    tabindex="0"
    @click="handleClick"
    @keydown.esc="handleEscape"
    @keydown.enter="handleEnter"
    @keydown.left="handleArrow($event, 'x', left)"
    @keydown.right="handleArrow($event, 'x', right)"
    @keydown.up="handleArrow($event, 'y', up)"
    @keydown.down="handleArrow($event, 'y', down)"
    @blur="blurColor"
    @focus="focusColor"
  >
    <template v-for="(item, index) in list" :key="item + ':' + index">
      <div :class="[prefixCls + '-picker-colors-wrapper']">
        <div :data-color-id="index">
          <div :style="{background: item}" :class="[prefixCls + '-picker-colors-wrapper-color']"></div>
          <div :ref="colorCircle + index"  class="_colorCircle" :data-index="index" :class="[prefixCls + '-picker-colors-wrapper-circle', hideClass]"></div>
        </div>
      </div>
      <br v-if="lineBreak(list, index)">
    </template>
  </div>
</template>

<script setup>

import {ref,inject, computed, reactive,onMounted} from "vue"

defineOptions({
  name:'RecommendedColors'
})

const ColorPickerInstance=inject('ColorPickerInstance')
const prefixCls=ref('haloe-color-picker')
const props=defineProps({
  list: {
    type: Array,
    default: undefined,
  }
})
const emits=defineEmits( ['picker-color', 'change'])

let columns =ref(12);

let colorCircle=ref("color-circle-")
const reference=ref('reference')
let rows = ref(Math.ceil(props.list.length / columns.value));
const normalStep = 1;


let left=ref( -normalStep);
let right=ref(normalStep);
let up=ref(-normalStep)
let down=ref(normalStep)
let powerKey=ref('shiftKey')
let grid=reactive({x: 1, y: 1})

const getLinearIndex= (grid)=> {
  return columns.value * (grid.y - 1) + grid.x - 1;
}

const getMaxLimit=(axis)=> {
  return axis === 'x' ? columns.value : rows.value;
}



const handleArrow= (e, axis, direction)=> {
  e.preventDefault();
  e.stopPropagation();

  this.blurColor();

  const grid = {...this.grid};

  if (e[this.powerKey]) {
    if (direction < 0) {
      grid[axis] = 1;
    } else {
      grid[axis] = getMaxLimit(axis);
    }
  } else {
    grid[axis] += direction;
  }

  const index = getLinearIndex(grid);

  if (index >= 0 && index < this.list.length) {
    this.grid[axis] = clamp(grid[axis], 1, getMaxLimit(axis));
  }

  this.focusColor();
}

const hideClass=computed(()=>prefixCls.value+'-hide')
const linearIndex=computed(()=>getLinearIndex(grid))
const currentCircle=computed(()=>(colorCircle.value+linearIndex.value))
// onMounted(() => {
//   console.log('currentCircle',currentCircle,colorCircle.value+linearIndex.value)
//   console.log(document.querySelectorAll('._colorCircle')[linearIndex.value])
// })
const blurColor= ()=> {
  // console.log(' currentCircle.value', currentCircle.value)
  document.querySelectorAll('._colorCircle')[linearIndex.value].classList.add(hideClass.value)
  // currentCircle.value.classList.add(hideClass.value);
}





const focusColor=()=> {
  // currentCircle.value.classList.remove(hideClass.value);
  document.querySelectorAll('._colorCircle')[linearIndex.value].classList.remove(hideClass.value)

}

const handleClick= (e, circle)=> {
  e.preventDefault();
  e.stopPropagation();

  reference.value.focus();

  const target = circle || e.target;
  const colorId = target.dataset.colorId || target.parentElement.dataset.colorId;

  if (colorId) {
    blurColor();
    const id = Number(colorId) + 1;
    grid.x = id % columns.value || columns.value;
    grid.y = Math.ceil(id / columns.value);
    focusColor();
    emits('picker-color', props.list[colorId]);
    emits('change', {hex: props.list[colorId], source: 'hex'});
  }
}

const handleEnter= (e)=> {
  handleClick(e, currentCircle.value);
}

const lineBreak= (list, index)=> {
  if (!index) {
    return false;
  }
  const nextIndex = index + 1;
  return nextIndex < list.length && nextIndex % columns.value === 0;
}

</script>

<style>

</style>